package com.rams.jhms.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.rams.jhms.dto.FSPropsFolderDTO;
import com.rams.jhms.logging.BaseLogger;

public class DerbySettingsFSFoldersDAO extends DerbyBaseDAO {
	
	public void addFolder(String path) {
		Connection con = getConnection();
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
            st = con.prepareStatement("SELECT id FROM settings_fs_folders WHERE path=?");
            st.setString(1, path);
            rs = st.executeQuery();

            if (!rs.next()) {
                close(rs);
                close(st);

                st = con.prepareStatement("INSERT INTO settings_fs_folders(path) VALUES(?)");
                st.setString(1, path);
                st.executeUpdate();
            }
        } catch (SQLException e) {
        	BaseLogger.error(this, e);
        } finally {
            close(con, st, rs);
        }
	}
	
	public List<FSPropsFolderDTO> getFolders() {
		Connection con = getConnection();
        PreparedStatement st = null;
        ResultSet rs = null;

        List<FSPropsFolderDTO> res = new ArrayList<FSPropsFolderDTO>();
        try {
        	
			st = con.prepareStatement("SELECT * FROM settings_fs_folders");
	        rs = st.executeQuery();
	        while (rs.next()) {
	        	FSPropsFolderDTO f = new FSPropsFolderDTO();
	        	f.setId(rs.getInt("id"));
	        	f.setPath(rs.getString("path"));
	        	res.add(f);
	        }
        } catch (SQLException sqle) {
        	BaseLogger.error(this, sqle);
        } catch (Exception e) {
        	BaseLogger.error(this, e);
		} finally {
			close(con, st, rs);
		}
		
		return res;
	}
	
	public void removeFolder(int folderId) {
		Connection con = getConnection();
        PreparedStatement st = null;

        try {
            st = con.prepareStatement("DELETE FROM settings_fs_folders WHERE id=?");
            st.setInt(1, folderId);
            st.execute();
        } catch (SQLException e) {
        	BaseLogger.error(this, e);
        } finally {
            close(st);
            close(con);
        }
	}
}
